package com.weaver.drools.common.support;

import java.net.SocketException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.weaver.drools.common.utils.ControllerUtil;
import com.weaver.drools.common.utils.ReturnMessage;
/**
 * 全局统一异常处理
 * 
 * @project: inventory
 * @author: zhouxinlei
 * @time：2018年9月6日 @version：ver 1.1
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	public static final String DEFAULT_ERROR_VIEW = "error/error";
	
	public static final String UNAUTHORIZED = "error/unauthorized";
	/**
	 * shiro权限处理异常
	 * @param request
	 * @return
	 */
	@ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String processUnauthenticatedException(HttpServletRequest request, UnauthorizedException exception) {
        request.setAttribute("message", exception.getMessage());
        LOGGER.error("============拦截shiro异常{}==================",exception);
        return UNAUTHORIZED;
    }
	@ExceptionHandler(value = SocketException.class)
	public String SocketErrorHandler(HttpServletRequest request,HttpServletResponse response,Exception exception) throws Exception {
		String cs = "";
		//判断是不是Ajax请求
		if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
			cs = ReturnMessage.messageData(ReturnMessage.FAIL, "数据库连接失败，请重新尝试！",null);
			ControllerUtil.writejsonAndSession(response,request,cs);
		}else{
			request.setAttribute("message", "数据库连接失败，请重新尝试！");
			return DEFAULT_ERROR_VIEW;
		}
		return null;
	}
	/**
	 * 全局处理Exception
	 * 
	 * @param request
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	public String defaultErrorHandler(HttpServletRequest request,Exception exception) throws Exception {
		request.setAttribute("message", exception.getMessage());
		LOGGER.error("============拦截全局异常{}==================",exception);
		return DEFAULT_ERROR_VIEW;
	}
}
